package cn.leedsoft.and.crimeintent.controller.run_tracker;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import cn.leedsoft.and.crimeintent.R;
import cn.leedsoft.and.crimeintent.manager.run_tracker.LastLocationLoader;
import cn.leedsoft.and.crimeintent.manager.run_tracker.RunLoader;
import cn.leedsoft.and.crimeintent.manager.run_tracker.RunManager;
import cn.leedsoft.and.crimeintent.model.run_tracker.Run;

import java.text.SimpleDateFormat;

/**
 * Created by leeds on 2016/9/5 15:10.
 */
public class RunFragment extends Fragment {//这个页面，可能需要加载多个数据源。所以应以内部类，实现loader
    private static final String TAG = "RunFragment";
    private Button mStartButton, mStopButton, mMapButton;
    private TextView mStartedTextView, mLatitudeTextView, mLongitudeTextView,
            mAltitudeTextView, mElapsedTimeTextView;
    private RunManager mRunManager;
    private Location mLastLocation;
    private Run mRun;
    public static final String ARG_RUN_ID = "ARG_RUN_ID";
    private static final int LOADER_RUN = 0;
    private static final int LOADER_LOCATION = 1;
    private LocationReceiver mLocationReceiver = new LocationReceiver() {
        @Override
        protected void onProviderEnabled(boolean enabled) {
            String toastText = enabled ? "gps available!" : "gps unavailable!";
            Toast.makeText(getActivity(), toastText, Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onLocationReceived(Context context, Location loc) {
            if (!mRunManager.isTrackingRun()) return;

            mLastLocation = loc;
            if (isVisible()) {
                updateUI();
            }
        }
    };

    public static RunFragment newInstance(long runId) {
        Bundle args = new Bundle();
        args.putLong(ARG_RUN_ID, runId);

        RunFragment fragment = new RunFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        mRunManager = RunManager.getInstance(getActivity());

        if (getArguments() != null && getArguments().getLong(ARG_RUN_ID, -1) != -1) {
            getLoaderManager().initLoader(LOADER_RUN, getArguments(), new RunLoaderCallback());//通知Run loader加载数据
            getLoaderManager().initLoader(LOADER_LOCATION, getArguments(), new LocationLoaderCallback());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.run_fragment, container, false);
        mStartButton = (Button) view.findViewById(R.id.run_btn_start);
        mStopButton = (Button) view.findViewById(R.id.run_btn_stop);
        mMapButton = (Button) view.findViewById(R.id.run_btn_map);
        View.OnClickListener btnClickLsr = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.run_btn_start:
                        if (mRun == null) {
                            mRun = mRunManager.startNewRun();
                        } else {
                            mRunManager.startTrackingRun(mRun);
                        }
                        updateUI();
                        break;
                    case R.id.run_btn_stop:
                        mRunManager.stopRun();
                        updateUI();
                        break;
                    case R.id.run_btn_map:
                        Intent intent = new Intent(getActivity(), RunMapActivity.class);
                        intent.putExtra(RunMapFragment.ARG_RUN_ID, mRun.getId());
                        startActivity(intent);
                        break;
                }
            }
        };
        mStartButton.setOnClickListener(btnClickLsr);
        mStopButton.setOnClickListener(btnClickLsr);
        mMapButton.setOnClickListener(btnClickLsr);

        mStartedTextView = (TextView) view.findViewById(R.id.run_tv_started);
        mLatitudeTextView = (TextView) view.findViewById(R.id.run_tv_latitude);
        mLongitudeTextView = (TextView) view.findViewById(R.id.run_tv_longitude);
        mAltitudeTextView = (TextView) view.findViewById(R.id.run_tv_altitude);
        mElapsedTimeTextView = (TextView) view.findViewById(R.id.run_tv_elapsed_time);
        updateUI();
        return view;
    }

    private void updateUI() {
        boolean started = mRunManager.isTrackingRun();

        mStartButton.setEnabled(!started);
        mStopButton.setEnabled(started && mRunManager.isTrackingRun(mRun));

        if (mRun != null) {
            mStartedTextView.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mRun.getStartDate()));
        }

        int durationSeconds = 0;
        if (mRun != null && mLastLocation != null) {
            durationSeconds = mRun.getDurationSeconds(mLastLocation.getTime());
            mLatitudeTextView.setText(String.valueOf(mLastLocation.getLatitude()));
            mLongitudeTextView.setText(String.valueOf(mLastLocation.getLongitude()));
            mAltitudeTextView.setText(String.valueOf(mLastLocation.getAltitude()));
            mMapButton.setEnabled(true);
        } else {
            mMapButton.setEnabled(false);
        }
        mElapsedTimeTextView.setText(Run.formatDurationSeconds(durationSeconds));
    }

    @Override
    public void onStart() {
        super.onStart();
        getActivity().registerReceiver(mLocationReceiver, new IntentFilter(RunManager.ACTION_LOCATION));
    }

    @Override
    public void onStop() {
        super.onStop();
        getActivity().unregisterReceiver(mLocationReceiver);
    }

    private class RunLoaderCallback implements LoaderManager.LoaderCallbacks<Run> {

        @Override
        public Loader<Run> onCreateLoader(int id, Bundle args) {//启动loader时，应传递相应的参数
            return new RunLoader(getActivity(), args.getLong(ARG_RUN_ID));
        }

        @Override
        public void onLoadFinished(Loader<Run> loader, Run data) {//loader加载完毕。在主线程上调用。
            mRun = data;//把加载的旅程保存在fragment的mRun实例变量里，并调用方法刷新显示更新的数据
            updateUI();//更新ui  应该在UI线程（主线程）上执行
        }

        @Override
        public void onLoaderReset(Loader<Run> loader) {

        }
    }

    private class LocationLoaderCallback implements LoaderManager.LoaderCallbacks<Location> {

        @Override
        public Loader<Location> onCreateLoader(int id, Bundle args) {//启动loader时，应传递相应的参数
            return new LastLocationLoader(getActivity(), args.getLong(ARG_RUN_ID));
        }

        @Override
        public void onLoadFinished(Loader<Location> loader, Location data) {//loader加载完毕。在主线程上调用。
            mLastLocation = data;
            updateUI();
        }

        @Override
        public void onLoaderReset(Loader<Location> loader) {

        }
    }
}
